/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entity.Regalo;
import entity.Utente;
import facade.RegaloFacadeLocal;
import facade.UtenteFacadeLocal;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

/**
 *
 * @author erola
 */
@MessageDriven(mappedName = "jms/WLMessage", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class WLMessageBean implements MessageListener {

    @EJB
    private RegaloFacadeLocal regaloFacade;
    @EJB
    private UtenteFacadeLocal utenteFacade;
    @Resource
    private MessageDrivenContext mdc;

    public WLMessageBean() {
    }

    @Override
    public void onMessage(Message message) {
        ObjectMessage msg = null;
        try {
            if (message instanceof ObjectMessage) {
                msg = (ObjectMessage) message;
                String username = msg.getStringProperty("username");
                String regalo = msg.getStringProperty("regalo");

                cancella(username, regalo);
            }
        } catch (Exception e) {
            mdc.setRollbackOnly();
        }
    }

    private void cancella(String username, String regalo) {
        //TROVO L'UTENTE
        List<Utente> utenti = utenteFacade.findAll();
        int i = 0;
        while (i < utenti.size() && !(utenti.get(i).getLogin()).equals(username)) {
            i++;
        }
        Utente utente = utenti.get(i);
        ArrayList<Regalo> regali = utente.getLista();

        //CANCELLO IL REGALO
        i = 0;
        while (i < regali.size() && !(((regali.get(i)).getNome()).equalsIgnoreCase(regalo))) {
            i++;
        }

        Regalo temp = regali.get(i);
        regali.remove(temp);
        utente.setLista(regali);
        regaloFacade.remove(temp);
        utenteFacade.edit(utente);
    }
}
